package com.yhc.server.exception;

import com.yhc.common.dto.BaseResult;
import com.yhc.common.util.ResultUtil;
import com.yhc.common.util.ServletUtil;
import com.yhc.server.consts.RequestHeader;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@Slf4j
@RestControllerAdvice(basePackages = "com.yhc.server")
public class SBFExceptionHandler {

    @ExceptionHandler(Exception.class)
    private BaseResult<?> handleException(Exception e) {
        String requestId = getRequestId();
        log.error("# request error, request id: {}", requestId, e);
        return ResultUtil.error();
    }

    @ExceptionHandler(SBFServiceException.class)
    private BaseResult<?> handleAccessException(SBFServiceException se) {
        log.warn("# request fail, {}", se.getMessage());
        return ResultUtil.fail(se);
    }

    @ExceptionHandler({MethodArgumentNotValidException.class, MissingServletRequestParameterException.class})
    public BaseResult<?> exceptionHandle(MethodArgumentNotValidException me) {
        log.warn("# request fail, {}", me.getBindingResult().getFieldError().getDefaultMessage());
        return ResultUtil.fail(me.getBindingResult().getFieldError().getDefaultMessage());
    }

    private String getRequestId() {
        HttpServletRequest request = ServletUtil.getRequest();
        String requestId = request.getHeader(RequestHeader.REQUEST_ID);
        if (StringUtils.isBlank(requestId) || requestId.length() <= 7) {
            return requestId;
        }
        return requestId.substring(requestId.length() - 7);
    }

}
